﻿using System;
using Castle.MicroKernel;
using Castle.MicroKernel.Registration;
using GdNet.WebFramework.Business.System;
using GdNet.WebFramework.Domain.Repositories.System;
using GdNet.WebFramework.Domain.System;
using Module = GdNet.WebFramework.Domain.System.Module;

namespace GdNet.WebFramework.Business.Impl.System
{
    public class ModuleLoaderService : IModuleLoaderService
    {
        private readonly IModuleRepository _moduleRepository;
        private readonly IKernel _kernel;

        public ModuleLoaderService(IKernel kernel, IModuleRepository moduleRepository)
        {
            _kernel = kernel;
            _moduleRepository = moduleRepository;
        }

        public void LoadActivatedModules()
        {
            var activeModules = _moduleRepository.GetAll();
            foreach (var module in activeModules)
            {
                foreach (var action in module.Actions)
                {
                    LoadAModule(module, action);
                }
            }
        }

        private void LoadAModule(Module module, ModuleAction action)
        {
            var actionTypeName = string.Format("{0}, {1}", action.ClassName, module.AssemblyName);
            var actionType = Type.GetType(actionTypeName);

            if (_kernel.HasComponent(actionType) == false)
            {
                _kernel.Register(Component.For(actionType).LifeStyle.PerWebRequest);
            }
        }

        public object ResolveService(Type actionType)
        {
            return _kernel.Resolve(actionType);
        }
    }
}
